#!/usr/bin/env python
# _*_ coding: utf-8 _*_
# @Time : 2020/7/15 22:37
# @Author : LZQ
# @Version：V 0.1
# @File : roles.py
# @desc :
# !/usr/bin/env python
# _*_ coding: utf-8 _*_
# @Time : 2020/7/15 17:04
# @Author : LZQ
# @Version：V 0.1
# @File : rights.py
# @desc : 所以权限相关的操作
from . import api, role
from __init__ import db, redis_store
from app.utils.status_code import RET
from app.utils.commons import tree
from flask import current_app, g, session, request, jsonify
from sqlalchemy.exc import IntegrityError
from sqlalchemy import or_, and_, desc
from app.models import Role, Permission
import json, time
from app.token_verify import verify


def getRoles_list(*kwargs):
    '''
    :param kwargs: rid存在则获取单个角色的权限，rid不存在则获取全部角色的权限
    :return:
    '''
    data = []
    if kwargs.__len__() == 1:
        rid = kwargs[0]
        try:
            role = Role.query.filter(Role.role_id == rid).first()
            list_1 = []
            list_2 = []
            list_3 = []
            role_dict = {}
            ps_ids = role.ps_ids.split(',')
            role_dict['id'] = role.role_id
            role_dict['roleName'] = role.role_name
            role_dict['roleDesc'] = role.role_desc
            permissions = Permission.query.filter(Permission.ps_id.in_(ps_ids)).all()
            # 将一级二级三级分类
            for permission in permissions:
                if permission.ps_level == '0':
                    list_1.append(permission)
                if permission.ps_level == '1':
                    list_2.append(permission)
                if permission.ps_level == '2':
                    list_3.append(permission)
            role_dict['children'] = tree(list_1, list_2, list_3)
            data.append(role_dict)
        except Exception as e:
            current_app.logger.error(e)
        return data
    elif kwargs.__len__() == 2:
        print(kwargs[0],kwargs[1])
        try:
            roles = Role.query.filter().paginate(kwargs[0],kwargs[1])
            for role in roles.items:
                list_1 = []
                list_2 = []
                list_3 = []
                role_dict = {}
                ps_ids = role.ps_ids.split(',')
                role_dict['id'] = role.role_id
                role_dict['roleName'] = role.role_name
                role_dict['roleDesc'] = role.role_desc
                permissions = Permission.query.filter(Permission.ps_id.in_(ps_ids)).all()
                # 将一级二级三级分类
                for permission in permissions:
                    if permission.ps_level == '0':
                        list_1.append(permission)
                    if permission.ps_level == '1':
                        list_2.append(permission)
                    if permission.ps_level == '2':
                        list_3.append(permission)
                role_dict['children'] = tree(list_1, list_2, list_3)
                data.append(role_dict)
        except Exception as e:
            current_app.logger.error(e)
        return data,roles.total


@role.route('/list', methods=['POST'])
@verify
def get_roles_list():
    '''
    获取角色的权限列表，层级展示
    :return:
    '''
    data = json.loads(request.get_data())
    pagenum = int(data.get('pagenum'))
    pagesize = int(data.get("pagesize"))

    data,total = getRoles_list(pagenum, pagesize)
    datas = {"data": data,"total":total, "meta": RET.ROLE_GET_LIST_SUCCESS}
    return jsonify(datas)

@role.route('/list', methods=['GET'])
@verify
def userSetRole_list():
    '''
    获取角色列表
    :return:
    '''
    data = []
    try:
        roles = Role.query.filter().all()
        for role in roles:
            data.append(role.to_dict())
    except Exception as e:
        current_app.logger.error(e)
    datas = {"data": data,"meta": RET.ROLE_GET_LIST_SUCCESS}
    return jsonify(datas)

@role.route('/exist', methods=['POST'])
@verify
def get_roleName_exist():
    '''
    获取角色的权限列表，层级展示
    :return:
    '''
    data = json.loads(request.get_data())
    role_name = data.get('role_name')
    try:
        count = Role.query.filter(Role.role_name == role_name).count()
        if count != 0:
            return jsonify(RET.ROLE_NAME_EXIST)
    except Exception as e:
        current_app.logger.error(e)
    return jsonify(RET.ROLE_NAME_DONET_EXIST)


@role.route('/<string:rid>/list', methods=['GET'])
@verify
def get_role_list(rid):
    '''
    获取角色的权限列表，层级展示
    :return:
    '''
    data = getRoles_list(rid)
    datas = {"data": data, "meta": RET.ROLE_GET_LIST_SUCCESS}
    return jsonify(datas)


@role.route('/<string:rid>/delete', methods=['DELETE'])
@verify
def delete_role(rid):
    '''
    删除角色
    :return:
    '''
    try:
        count = Role.query.filter(Role.role_id == rid).delete()
        if count == 0:
            return jsonify(RET.ROLE_DELETE_FAIL)
        db.session.commit()
    except Exception as e:
        current_app.logger.error(e)
    return jsonify(RET.ROLE_DELETE_SUCCESS)


@role.route('/<string:RID>/rights/<string:right>', methods=['DELETE'])
@verify
def deletRoleRights(RID, right):
    '''
    删除角色的权限
    :param RID: 角色id
    :param right: 权限id
    :return:
    '''
    print(RID, right)
    if not all([RID, right]):
        return jsonify(RET.PARAMS_NOTALL)
    try:
        role = Role.query.filter(Role.role_id == RID).first()
        ps_pids = role.ps_ids.split(',')
        for ps_id in ps_pids:
            if ps_id == right:
                ps_pids.remove(ps_id)
        role.ps_ids = ",".join(ps_pids)
        print(",".join(ps_pids))
        db.session.merge(role)
        db.session.commit()
    except Exception as e:
        db.session.rollback()
        current_app.logger.error(e)
        return jsonify(RET.ROLE_DELETE_PERMISSION_FAIL)
    data = {"data": getRoles_list(RID), "meta": RET.ROLE_DELETE_PERMISSION_SUCCESS}
    return jsonify(data)


@role.route('/add', methods=['POST'])
@verify
def addRole():
    '''
    只添加角色，不分配权限
    :return: code = 10113 成功 10114 失败
    '''
    data = json.loads(request.get_data())
    role_name = data.get('role_name')
    role_desc = data.get('role_desc')
    if not all([role_name, role_desc]):
        return jsonify(RET.PARAMS_NOTALL)
    try:
        role = Role()
        role.role_name = role_name
        role.role_desc = role_desc
        role.ps_ids = '0'
        db.session.add(role)
        db.session.commit()
    except Exception as e:
        db.session.rollback()
        current_app.logger.error(e)
        return jsonify(RET.ROLE_ADD_FAIL)
    return jsonify(RET.ROLE_ADD_SUCCESS)


@role.route('/add/rights', methods=['POST'])
@verify
def addRoleRights():
    '''
    添加角色的权限
    :return:
    '''
    data = json.loads(request.get_data())
    rid = data.get('role_id')
    right = data.get('ps_ids')
    if not all([rid]):
        return jsonify(RET.PARAMS_NOTALL)
    try:
        role = Role.query.filter(Role.role_id == rid).first()
        if right:
            role.ps_ids = str(right)
        else:
            role.ps_ids = '0'
        db.session.merge(role)
        db.session.commit()
    except Exception as e:
        db.session.rollback()
        current_app.logger.error(e)
        return jsonify(RET.ROLE_UPDATE_PERMISSION_FAIL)
    return jsonify(RET.ROLE_UPDATE_PERMISSION_SUCCESS)


@role.route("/update", methods=["POST"])
@verify
def updateRole():
    datas = []
    data = json.loads(request.get_data())
    role_id = data.get("role_id")
    role_name = data.get('role_name')
    role_desc = data.get("role_desc")
    print(role_desc, role_name, role_id)
    if not all([role_name, role_desc, role_id]):
        return jsonify(RET.PARAMS_NOTALL)
    try:
        role = Role.query.filter(Role.role_id == role_id).first()
        role.role_name = role_name
        role.role_desc = role_desc
        db.session.merge(role)
        db.session.commit()
        datas.append(role.to_dict())
        datas.append(RET.ROLE_UPDATE_SUCCESS)
    except Exception as e:
        db.session.rollback()
        current_app.logger.error(e)
        return jsonify(RET.DATABASE_ERROR)
    return jsonify(datas)
